package com.code.user.controller;


import com.code.common.annotation.Idempotent;
import com.code.common.model.ResultVO;
import com.code.user.model.RoleDO;
import com.code.user.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 *
 * @author Yan
 * @since 2023-04-17
 */
@Api(value = "角色控制器", description = "角色控制器")
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @ApiOperation(value = "保存角色", notes = "保存角色")
    @PostMapping("/save")
    @Idempotent(key = "#roleDO.name")
    public ResultVO<String> save(@RequestBody @Valid RoleDO roleDO) {
        boolean result = roleService.save(roleDO);
        return result ? ResultVO.OK("保存成功") : ResultVO.ERROR("保存失败");
    }

    @ApiOperation(value = "删除角色", notes = "删除角色")
    @DeleteMapping("/delete/{id}")
    public ResultVO<String> delete(@PathVariable(name = "id") String id) {
        boolean result = roleService.removeById(id);
        return result ? ResultVO.OK("删除成功") : ResultVO.ERROR("删除失败");
    }

    @ApiOperation(value = "修改角色", notes = "修改角色")
    @PutMapping("/update")
    @Idempotent(key = "#roleDO.name")
    public ResultVO<String> update(@RequestBody @Valid RoleDO roleDO) {
        boolean result = roleService.updateById(roleDO);
        return result ? ResultVO.OK("修改成功") : ResultVO.ERROR("修改成功");
    }

    @ApiOperation(value = "根据ID查询角色", notes = "根据ID查询角色")
    @GetMapping("search")
    public ResultVO<RoleDO> search(@RequestParam(name = "id") String id) {
        RoleDO roleDO = roleService.getById(id);
        return ResultVO.OK(roleDO);
    }

    @ApiOperation(value = "查询所有角色", notes = "查询所有角色")
    @GetMapping("searchAll")
    public ResultVO<List<RoleDO>> searchAll() {
        List<RoleDO> roleList = roleService.list();
        return ResultVO.OK(roleList);
    }

    @ApiOperation(value = "绑定角色权限", notes = "绑定角色权限")
    @PostMapping("/bindPermission")
    public ResultVO bindPermission(@RequestParam(name = "rid") String rid,
                                   @RequestParam(name = "pid") String pid) {
        boolean result = roleService.bindPermission(rid, pid);
        return result ? ResultVO.OK() : ResultVO.ERROR();
    }

    @ApiOperation(value = "解绑角色权限", notes = "解绑角色权限")
    @DeleteMapping("/unbindPermission/")
    public ResultVO unbindPermission(@RequestParam(name = "rid") String rid,
                                     @RequestParam(name = "pid") String pid) {
        boolean result = roleService.unbindPermission(rid, pid);
        return result ? ResultVO.OK() : ResultVO.ERROR();
    }

}
